<?php
declare(strict_types=1);
require_once __DIR__ . "/centre-branding.php";

function canCloseStudent(array $u): bool
{
    return central($u) || $u['role']==='branch_manager';
}

function studentClosure(int $studentId): ?array
{
    return one('SELECT * FROM student_closures WHERE original_student_id=?',[$studentId]);
}

function ensureStudentOpen(int $studentId): void
{
    if (studentClosure($studentId)) {
        throw new InvalidArgumentException('Dossier clôturé : les nouvelles inscriptions, modifications et opérations sont bloquées. Consultez les archives.');
    }
}

function closureQuote(int $studentId): array
{
    $language=rows('SELECT p.* FROM language_payments p JOIN enrollments e ON e.id=p.enrollment_id WHERE e.student_id=? ORDER BY p.id',[$studentId]);
    $support=rows('SELECT p.* FROM support_payments p JOIN enrollments e ON e.id=p.enrollment_id WHERE e.student_id=? ORDER BY p.id',[$studentId]);
    $total=0;
    foreach($language as $p){if($p['cancelled_at']===null){$total+=(int)$p['training_cents']+(int)$p['registration_cents'];}}
    foreach($support as $p){$total+=(int)$p['amount_cents'];}
    $snapshot=[
        'enrollments'=>rows('SELECT * FROM enrollments WHERE student_id=? ORDER BY id',[$studentId]),
        'language_payments'=>$language,'support_payments'=>$support,
        'renewals'=>rows('SELECT r.* FROM language_renewals r JOIN enrollments e ON e.id=r.enrollment_id WHERE e.student_id=? ORDER BY r.id',[$studentId]),
        'cards'=>rows('SELECT * FROM loyalty_cards WHERE student_id=? ORDER BY id',[$studentId]),
        'loyalty'=>rows('SELECT * FROM loyalty_transactions WHERE student_id=? ORDER BY id',[$studentId]),
        'referrals'=>rows('SELECT * FROM loyalty_referrals WHERE referrer_student_id=? OR referred_student_id=? ORDER BY id',[$studentId,$studentId]),
        'attendance'=>rows('SELECT * FROM language_student_attendance WHERE student_id=? ORDER BY session_id',[$studentId]),
        'sessions'=>rows('SELECT * FROM language_sessions WHERE student_id=? ORDER BY id',[$studentId]),
        'documents'=>rows('SELECT * FROM student_documents WHERE student_id=? ORDER BY id',[$studentId]),
    ];
    $json=json_encode($snapshot,JSON_THROW_ON_ERROR|JSON_INVALID_UTF8_SUBSTITUTE);
    return ['amount'=>$total,'snapshot'=>$snapshot,'json'=>$json,'hash'=>hash('sha256',$json)];
}

function closeStudent(array $u): int
{
    if (!canCloseStudent($u)) {fail();}
    $studentId=idValue('student_id');
    $mode=choice('closure_mode',['refund_archive'=>1,'test_delete'=>1]);
    $reason=$mode==='test_delete'?'Suppression de fiche d’essai confirmée':'Restitution totale et archivage confirmés';
    $confirmation=val('closure_confirm',3);
    $key=val('submission_key',32,true);
    $expected=val('expected_snapshot',64,true);
    if(!preg_match('/^[0-9a-f]{32}$/D',$key) || !preg_match('/^[0-9a-f]{64}$/D',$expected)) {throw new InvalidArgumentException('Rechargez la page de confirmation.');}
    if ($confirmation!=='yes') {throw new InvalidArgumentException('Confirmez l’action pour continuer.');}
    $date=$mode==='refund_archive'?dateValue('refunded_on'):null;
    $method=$mode==='refund_archive'?choice('refund_method',LANGUAGE_PAYMENT_METHODS):null;
    if($mode==='refund_archive' && (!$date || $date>date('Y-m-d'))){throw new InvalidArgumentException('Indiquez la date réelle de restitution, au plus tard aujourd’hui.');}
    db()->beginTransaction();
    try {
        $existing=one('SELECT * FROM student_closures WHERE original_student_id=? OR submission_key=?',[$studentId,$key]);
        if($existing){
            branchAllowed($u,(int)$existing['branch_id']);
            if((int)$existing['original_student_id']!==$studentId || $existing['submission_key']!==$key || $existing['operation']!==$mode || (int)$existing['actor_id']!==(int)$u['id'] || $existing['reason']!==$reason || $existing['refunded_on']!==$date || $existing['refund_method']!==$method) {throw new InvalidArgumentException('Une clôture existe déjà. Consultez les archives.');}
            db()->commit();return (int)$existing['id'];
        }
        $student=studentAllowed($u,$studentId,true);
        one('SELECT id FROM students WHERE id=? FOR UPDATE',[$studentId]);
        $quote=closureQuote($studentId);
        if(!hash_equals($expected,$quote['hash'])){throw new InvalidArgumentException('Le dossier a changé depuis son affichage. Rechargez et vérifiez à nouveau les montants.');}
        if($mode==='test_delete'){
            if(val('test_ack',3)!=='yes'){throw new InvalidArgumentException('Confirmez explicitement que toutes les données sont fictives et qu’aucune somme réelle n’a été reçue.');}
            if($quote['snapshot']['sessions']){throw new InvalidArgumentException('Ce dossier est lié à des séances individuelles. Leur examen est nécessaire avant une suppression définitive. Utilisez la clôture si le client est réel.');}
            if(one('SELECT id FROM loyalty_referrals WHERE referrer_student_id=?',[$studentId])){throw new InvalidArgumentException('Ce dossier est parrain d’un autre élève. Traitez d’abord les dossiers de test parrainés afin de préserver leurs liens.');}
            if(one("SELECT t.id FROM loyalty_transactions t WHERE t.student_id=? AND t.kind='redemption' AND NOT EXISTS(SELECT 1 FROM language_payments p JOIN enrollments e ON e.id=p.enrollment_id WHERE e.student_id=t.student_id AND p.loyalty_transaction_id=t.id)",[$studentId])){throw new InvalidArgumentException('Un crédit a été consommé : examen administratif nécessaire avant la suppression.');}
        }
        if ($mode==='refund_archive') {
            foreach($quote['snapshot']['language_payments'] as $payment) {
                if($payment['cancelled_at']===null) {restorePaymentLoyalty($payment,$studentId,(int)$u['id']);}
            }
        }
        // Reverse awarded referral rewards before disabling or deleting the holder.
        foreach($quote['snapshot']['referrals'] as $referral){
            if($referral['status']!=='cancelled'){
                reverseLoyaltyReferral($referral,(int)$u['id'],'Dossier clôturé : '.$reason);
                run("UPDATE loyalty_referrals SET status='cancelled',cancelled_at=CURRENT_TIMESTAMP,cancelled_by=?,cancellation_reason=? WHERE id=?",[$u['id'],$reason,$referral['id']]);
            }
        }
        foreach($quote['snapshot']['renewals'] as $renewal){
            if($renewal['cancelled_at']===null){
                if($mode==='refund_archive'){reverseLanguageRenewalBonus($renewal,$studentId,(int)$u['id']);}
                run("UPDATE language_renewals SET reward_status='cancelled',cancelled_at=CURRENT_TIMESTAMP,cancelled_by=?,cancellation_reason=? WHERE id=?",[$u['id'],$reason,$renewal['id']]);
            }
        }
        if($mode==='refund_archive'){
            // A loyalty balance is credit, never extra cash to reimburse.
            $balance=(int)one('SELECT COALESCE(SUM(amount_cents),0) n FROM loyalty_transactions WHERE student_id=?',[$studentId])['n'];
            if($balance<0){throw new InvalidArgumentException('Solde fidélité incohérent : régularisation nécessaire.');}
            if($balance>0){
                $card=one('SELECT id FROM loyalty_cards WHERE student_id=?',[$studentId]);
                run("INSERT INTO loyalty_transactions(student_id,card_id,branch_id,actor_user_id,kind,amount_cents,reference_key,note) VALUES(?,?,?,?,'reversal',?,?,?)",[$studentId,$card['id']??null,$student['branch_id'],$u['id'],-$balance,'closure-'.$studentId,'Crédit fidélité annulé à la clôture, sans restitution en espèces.']);
            }
        }
        $files=array_column($quote['snapshot']['documents'],'stored_path');
        run('INSERT INTO student_closures(original_student_id,student_id,student_code,student_name,branch_id,operation,amount_cents,refunded_on,refund_method,actor_id,reason,submission_key,snapshot_json,retained_files_json) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)',[$studentId,$studentId,$student['student_code'],$student['full_name'],$student['branch_id'],$mode,$mode==='refund_archive'?$quote['amount']:0,$date,$method,$u['id'],$reason,$key,$quote['json'],json_encode($files,JSON_THROW_ON_ERROR)]);
        $closureId=(int)db()->lastInsertId();
        if(function_exists("captureReceiptIdentity")){captureReceiptIdentity("closure",$closureId,(int)$student["branch_id"]);}
        if($mode==='test_delete'){
            run('DELETE FROM loyalty_referrals WHERE referred_student_id=?',[$studentId]);
            // Release self references before deleting this student's renewal cycles.
            run('UPDATE language_renewals SET previous_renewal_id=NULL,bonus_transaction_id=NULL WHERE enrollment_id IN (SELECT id FROM enrollments WHERE student_id=?)',[$studentId]);
            run('UPDATE language_payments SET replaces_payment_id=NULL WHERE enrollment_id IN (SELECT id FROM enrollments WHERE student_id=?)',[$studentId]);
            run('DELETE FROM language_payments WHERE enrollment_id IN (SELECT id FROM enrollments WHERE student_id=?)',[$studentId]);
            run('DELETE FROM language_renewals WHERE enrollment_id IN (SELECT id FROM enrollments WHERE student_id=?)',[$studentId]);
            run('DELETE FROM loyalty_transactions WHERE student_id=?',[$studentId]);
            run("UPDATE loyalty_cards SET student_id=NULL,issued_at=NULL,status=CASE WHEN status='active' THEN 'available' ELSE status END WHERE student_id=?",[$studentId]);
            run('DELETE FROM support_payments WHERE enrollment_id IN (SELECT id FROM enrollments WHERE student_id=?)',[$studentId]);
            run('DELETE FROM language_student_attendance WHERE student_id=?',[$studentId]);
            run('DELETE FROM student_documents WHERE student_id=?',[$studentId]);
            run('DELETE FROM enrollments WHERE student_id=?',[$studentId]);
            run('UPDATE student_closures SET student_id=NULL WHERE id=?',[$closureId]);
            run('DELETE FROM students WHERE id=?',[$studentId]);
            run("DELETE FROM users WHERE id=? AND role='student'",[$student['user_id']]);
            // Private attachment bytes are deliberately retained with the audit for recovery.
        } else {
            run('UPDATE users SET is_active=0 WHERE id=?',[$student['user_id']]);
            run("UPDATE enrollments SET status='completed' WHERE student_id=? AND status='active'",[$studentId]);
            run("UPDATE loyalty_cards SET status='blocked' WHERE student_id=? AND status='active'",[$studentId]);
        }
        db()->commit();return $closureId;
    } finally {if(db()->inTransaction()){db()->rollBack();}}
}

function renderClosureAction(array $u, int $studentId): void
{
    if(canCloseStudent($u)){echo ' · <a href="?page=student_close&amp;id='.$studentId.'">Supprimer / Clôturer</a>';}
}

function renderStudentClose(array $u): void
{
    if(!canCloseStudent($u)){fail();}
    $raw=$_GET['id']??'';
    if(!is_string($raw) || !preg_match('/^[1-9][0-9]{0,9}$/D',$raw)){fail('Élève introuvable.',404);}
    $student=studentAllowed($u,(int)$raw);
    $id=(int)$student['id'];
    if(studentClosure($id)){echo '<p>Dossier déjà clôturé. Consultez les archives.</p>';return;}
    $quote=closureQuote($id);
    echo '<section class="panel"><h2>Supprimer / Clôturer · '.h($student['full_name']).'</h2><p><a href="?page=dossier&amp;id='.$id.'">Retour au dossier</a></p><p>Encaissements actifs enregistrés : <strong>'.h(moneyValue($quote['amount'])).' DH</strong>. Les paiements corrigés/annulés sont exclus. Le crédit fidélité n’est pas remboursable en espèces.</p>';
    echo '<details><summary class="button">Client réel — remboursement total et archivage</summary><p>Réservé à une annulation totale avec restitution de toutes les sommes reçues. Les reçus et les historiques sont conservés. Vérifiez les montants avant de restituer l’argent; en cas de bonus déjà consommé, faites régulariser le crédit avant toute restitution.</p>';
    startForm('student_close',['student_id'=>$id,'closure_mode'=>'refund_archive','expected_snapshot'=>$quote['hash'],'submission_key'=>bin2hex(random_bytes(16))]);
    echo '<p>Montant total à restituer : <strong>'.h(moneyValue($quote['amount'])).' DH</strong>. Enregistrer seulement après la restitution réelle de ce montant.</p>';
    field('refunded_on','Date réelle de restitution',date('Y-m-d'),'date',true);
    selectField('refund_method','Méthode de restitution',LANGUAGE_PAYMENT_METHODS,'cash');
    echo '<label><input type="checkbox" name="closure_confirm" value="yes" required> Je confirme la restitution réelle du montant affiché et l’archivage de ce dossier.</label>';
    endForm('Confirmer la restitution réelle et archiver');echo '</details>';
    echo '<details><summary>Fiche d’essai — suppression définitive</summary><p>Uniquement des données fictives : aucune somme réellement encaissée. Le compte, les inscriptions, paiements fictifs et liens de fidélité sont supprimés. Une trace administrative et les pièces jointes privées sont conservées pour récupération. Les séances individuelles ou crédits consommés nécessitent un examen séparé.</p>';
    startForm('student_close',['student_id'=>$id,'closure_mode'=>'test_delete','expected_snapshot'=>$quote['hash'],'submission_key'=>bin2hex(random_bytes(16))]);
    echo '<input type="hidden" name="test_ack" value="yes"><label><input type="checkbox" name="closure_confirm" value="yes" required> Je confirme la suppression de cette fiche d’essai : toutes ses données sont fictives, sans encaissement réel.</label>';
    endForm('Supprimer définitivement cette fiche d’essai');echo '</details></section>';
}

function renderStudentClosureArchives(array $u): void
{
    if(!canCloseStudent($u)){fail();}
    [$where,$params]=branchScope($u,'c.branch_id');
    $items=rows('SELECT c.*,u.full_name actor FROM student_closures c JOIN users u ON u.id=c.actor_id WHERE '.$where.' ORDER BY c.id DESC LIMIT 200',$params);
    echo '<section class="panel"><h2>Archives des clôtures</h2><p>Les remboursements ci-dessous sont des sorties de caisse séparées des encaissements d’origine. Les sommes des anciennes pages de paiement restent des encaissements bruts : elles ne constituent pas un solde net après remboursement.</p>';
    tableView(['Référence','Élève','Opération','Restitué (DH)','Date','Employé','Action'],$items,function($r){cell('EM-R-'.str_pad((string)$r['id'],8,'0',STR_PAD_LEFT));cell($r['student_name']);cell($r['operation']==='test_delete'?'Fiche d’essai supprimée':'Remboursé et archivé');cell(moneyValue((int)$r['amount_cents']));cell($r['refunded_on']??$r['created_at']);cell($r['actor']);echo '<td><a href="?page=student_closure_receipt&amp;id='.(int)$r['id'].'">Détail / PDF</a>';if($r['student_id']!==null){echo ' · <a href="?page=dossier&amp;id='.(int)$r['student_id'].'">Dossier archivé</a>';}echo '</td>';});
    echo '</section>';
}

function printStudentClosure(array $u): void
{
    if(!canCloseStudent($u)){fail();}
    $raw=$_GET['id']??'';
    if(!is_string($raw) || !preg_match('/^[1-9][0-9]{0,9}$/D',$raw)){fail('Archive introuvable.',404);}
    $c=one('SELECT c.*,u.full_name actor FROM student_closures c JOIN users u ON u.id=c.actor_id WHERE c.id=?',[(int)$raw]);
    if(!$c){fail('Archive introuvable.',404);}branchAllowed($u,(int)$c['branch_id']);
    echo '<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>Clôture EM-R-'.h($c['id']).'</title><link rel="stylesheet" href="student-closure.css"><link rel="stylesheet" href="centre-branding.css"></head><body><p class="no-print">Ctrl + P : imprimer / enregistrer au format PDF.</p>';
    renderReceiptIdentity('closure',(int)$c['id']);
    echo '<h2>'.($c['operation']==='test_delete'?'FICHE D’ESSAI SUPPRIMÉE — AUCUN REMBOURSEMENT RÉEL':'REÇU DE REMBOURSEMENT TOTAL').'</h2>';
    echo '<p>Référence EM-R-'.str_pad(h($c['id']),8,'0',STR_PAD_LEFT).'<br>Élève : '.h($c['student_name']).'<br>Code : '.h($c['student_code']??'—').'<br>Montant restitué : <strong>'.h(moneyValue((int)$c['amount_cents'])).' DH</strong><br>Date : '.h($c['refunded_on']??$c['created_at']).'<br>Méthode : '.h(LANGUAGE_PAYMENT_METHODS[$c['refund_method']]??'Sans objet').'<br>Enregistré par : '.h($c['actor']).'<br>Motif : '.h($c['reason']).'</p>';
    $snapshot=json_decode($c['snapshot_json'],true,512,JSON_THROW_ON_ERROR);
    echo '<h3>Encaissements d’origine</h3><ul>';
    foreach($snapshot['language_payments'] as $p){if($p['cancelled_at']===null){echo '<li>'.h(languageReceiptNumber((int)$p['id'])).' · '.h(moneyValue((int)$p['training_cents']+(int)$p['registration_cents'])).' DH'.($c['operation']==='test_delete'?' · Donnée fictive supprimée':'').'</li>';}}
    foreach($snapshot['support_payments'] as $p){echo '<li>Soutien n° '.h($p['id']).' · '.h(moneyValue((int)$p['amount_cents'])).' DH'.($c['operation']==='test_delete'?' · Donnée fictive supprimée':'').'</li>';}
    echo '</ul><p>Signature du bénéficiaire : __________________________</p><p>Signature / cachet du centre : __________________________</p>';
    renderReceiptFooter('closure',(int)$c['id']);
    echo '</body></html>';
}
